package com.liu.util;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadUtil {
	/**
	 * 批量上传工具类 
	 * @author arry
	 * @param request 请求
	 * @param reponse 响应
	 * @return HashMap<String, Object> 集合
	 * 
	 */
	public static HashMap<String, Object> uploadFiles(HttpServletRequest resquest,HttpServletResponse response){
		
		HashMap<String, Object> map = new HashMap<String,Object>();
		
		String fileName;
		
		try{
			resquest.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			// 获取文件上传目录
			String realPath = resquest.getRealPath("/");
			String dirPath = realPath + "/upload";
			// 定义上传目录
			File dirFile = new File(dirPath);
			System.out.println("dirPath--"+dirPath);
			if(!dirFile.exists()){
				dirFile.mkdirs();
			}
			// 上传操作
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			
			List items = upload.parseRequest(resquest);
			if(null != items){
				Iterator itr = items.iterator();
				while(itr.hasNext()){
					FileItem item = (FileItem)itr.next();
					if(item.isFormField()){
						continue;
					} else{
						// 文件名
						String name = item.getName();
						int i = name.lastIndexOf(".");
						String ext = name.substring(i, name.length());
						// 文件重命名
						fileName = new Date().getTime() + ext;
						File saveFile = new File(dirPath,fileName);
						item.write(saveFile);
						map.put("name", item.getName());
						map.put("newName", fileName);
						map.put("size", item.getSize());
						map.put("url", "upload/"+fileName);
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return map;
	}
	
	
	public static void main(String[] args){
		
		
	}
	
}
